package com.dy.yunying.biz.controller.prize;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.entity.prize.PrizePush;
import com.dy.yunying.api.entity.usergroup.UserGroup;
import com.dy.yunying.api.enums.*;
import com.dy.yunying.api.req.prize.PrizeConfigReq;
import com.dy.yunying.api.req.prize.PrizeOnlineOrOfflineReq;
import com.dy.yunying.api.req.prize.PrizePushReq;
import com.dy.yunying.api.req.prize.PrizeSortReq;
import com.dy.yunying.api.utils.CheckUtils;
import com.dy.yunying.biz.service.prize.PrizePushService;
import com.dy.yunying.biz.service.usergroup.UserGroupService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.StringUtil;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 奖励推送表
 *
 * @author chenxiang
 * @version 2022-04-25 16:25:27 table: prize_push
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/prizePush")
public class PrizePushController extends PrizeBaseController {

	private final PrizePushService prizePushService;

	private final UserGroupService userGroupService;

	/**
	 * 分页列表
	 * @param record
	 * @return
	 */
	@RequestMapping("/getPage")
	public R getPage(@RequestBody PrizePushReq record) {
		return prizePushService.getPage(record);
	}

	/**
	 * 新增
	 * @param record
	 * @return
	 */
	@RequestMapping("/create")
	@SysLog("创建推送奖励")
	public R create(@RequestBody PrizePushReq record) {
		// 验证入参
		R result = checkParams(record);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		record.setId(null);
		return prizePushService.createEdit(record);
	}

	/**
	 * 编辑
	 * @param record
	 * @return
	 */
	@RequestMapping("/edit")
	@SysLog("编辑推送奖励")
	public R edit(@RequestBody PrizePushReq record) {
		if (StringUtils.isBlank(record.getId())) {
			return R.failed("未获取到唯一主键ID");
		}
//		List<PrizePush> list = prizePushService
//				.list(Wrappers.<PrizePush>lambdaQuery().eq(PrizePush::getId, record.getId())
//						.eq(PrizePush::getDeleted, 0).eq(PrizePush::getStatus, PrizePushStatusEnum.STOP.getType()));
//		if (CollectionUtils.isEmpty(list)) {
//			return R.failed("当前状态无法进行编辑");
//		}
		// 验证入参
		R result = checkParams(record);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		return prizePushService.createEdit(record);
	}

	/**
	 * 推送顺序编辑接口
	 * @param req
	 * @return
	 */
	@RequestMapping("/showSortEdit")
	public R sortNumberEdit(@Valid PrizeSortReq req) {
		PrizePush prizePush = new PrizePush();
		prizePush.setId(req.getId());
		prizePush.setShowSort(req.getShowSortNumber());
		return R.ok(prizePushService.updateById(prizePush),"排序编辑成功");
	}

	/**
	 * 删除奖励推送
	 * @return
	 */
	@RequestMapping("/deleteById")
	@SysLog("删除奖励推送")
	public R delete(@RequestParam("id") Long id) {
		return prizePushService.doRemoveById(id);
	}

	/**
	 * 启用停用
	 * @param req
	 * @return
	 */
	@RequestMapping("/startOrStop")
	@SysLog("启用停用奖励推送")
	public R prizePushStartOrStop(@RequestBody PrizeOnlineOrOfflineReq req) {
		return prizePushService.prizePushStartOrStop(req);
	}

	/**
	 * 复制奖励推送
	 * @return
	 */
	@RequestMapping("/copy")
	@SysLog("复制奖励推送")
	public R prizePushCopy(@RequestParam("id") Long id){
		R result = prizePushService.copy(id);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		return R.ok(0,"奖励推送复制成功");
	}

	/**
	 * 新增编辑 - 参数验证
	 * @param record
	 * @return
	 */
	public R checkParams(PrizePushReq record) {
		// 时间验证
		if (StringUtils.isBlank(record.getStartTime()) || StringUtils.isBlank(record.getEndTime())) {
			return R.failed("开始时间或结束时间不能为空");
		}
		Date startTime = DateUtils.stringToDate(record.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
		Date endTime = DateUtils.stringToDate(record.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
		if (startTime.getTime() > endTime.getTime()) {
			return R.failed("开始时间不能大于结束时间");
		}
		if (System.currentTimeMillis() > endTime.getTime()) {
			return R.failed("结束时间不能小于当前时间");
		}
		// 游戏，区服，渠道验证
		if (CollectionUtils.isEmpty(record.getGameList())) {
			return R.failed("请选择游戏范围");
		}
		if (CollectionUtils.isEmpty(record.getAreaList())) {
			return R.failed("请选择区服范围");
		}
		if (CollectionUtils.isEmpty(record.getChannelList())) {
			return R.failed("请选择渠道范围");
		}
		// 推送节点验证
		if (StringUtils.isBlank(record.getPushType())) {
			return R.failed("请选择推送节点");
		}
		if (Objects.isNull(record.getPushTarget())){
			return R.failed("请选择推送目标");
		}
		if (!PushTypeEnum.ONLYONCE.getType().equals(Integer.valueOf(record.getPushType()))
				&& StringUtils.isBlank(record.getPushNode())) {
			return R.failed("请选择推送节点");
		}
		if (PushTypeEnum.THENEXTDAY.getType().equals(Integer.valueOf(record.getPushType()))) {
			String pushInterval = record.getPushInterval();
			if (StringUtils.isBlank(pushInterval)) {
				return R.failed("请输入推送节点相隔天数");
			}
			if (!CheckUtils.checkInt(pushInterval)) {
				return R.failed("请输入正整数相隔天数");
			}
			if (Integer.valueOf(pushInterval) < 1 || Integer.valueOf(pushInterval) > 999) {
				return R.failed("相隔天数应为1~999");
			}
		} else if (PushTypeEnum.WEEKLY.getType().equals(Integer.valueOf(record.getPushType()))) {
			if (StringUtils.isBlank(record.getPushInterval())) {
				return R.failed("请选择每周推送节点");
			}
		}
		if (StringUtils.isBlank(record.getPushPrizeType())) {
			return R.failed("请选择推送类型");
		}
		if (PushPrizeTypeEnum.MUTI.getType().equals(Integer.valueOf(record.getPushPrizeType()))) {
			if (StringUtils.isBlank(record.getPopupMold())) {
				return R.failed("请选择推送方式");
			}
			Integer popupMold = Integer.valueOf(record.getPopupMold());
			if (PopupMoldEnum.IMAGE.getType().equals(popupMold)
					|| PopupMoldEnum.BANNER.getType().equals(popupMold) || PopupMoldEnum.MSG.getType().equals(popupMold)) {
				if (record.getTitle().length() < 1 || record.getTitle().length() > 20) {
					return R.failed("请输入1~20个字的标题");
				}
				if (StringUtils.isBlank(record.getDescription())) {
					return R.failed("请输入描述");
				}
			}
			if (!PopupMoldEnum.MSG.getType().equals(popupMold)) {
				if (StringUtils.isBlank(record.getIcon())) {
					return R.failed("请上传icon");
				}
				if (StringUtils.isBlank(record.getOpenType())) {
					return R.failed("请选择推送跳转");
				}
				if (PrizeOpenTypeEnum.SDK.getType().equals(Integer.valueOf(record.getOpenType()))) {
					if (StringUtils.isBlank(record.getMenuTitle())) {
						return R.failed("请选择功能定位跳转菜单");
					}
					String[] split = record.getMenuTitle().split(",");
					if (split.length<2) {
						return R.failed("请选择功能定位跳转菜单");
					}

					if (record.getMenuTitle().startsWith("红包")) {
						if (split.length<=1){
							return R.failed("请选择跳转红包类型");
						}
					}
					else if (record.getMenuTitle().startsWith("活动")) {
						//1红包活动 2签到活动
						if (StringUtils.isBlank(record.getSkipMold())) {
							return R.failed("请选择跳转活动类型");
						}
						if ("1".equals(record.getSkipMold()) || "2".equals(record.getSkipMold())) {
							//具体红包活动的id
							if (StringUtils.isBlank(record.getSkipId())) {
								return R.failed("请选择跳转活动");
							}
						}
					}
				} else if (PrizeOpenTypeEnum.BROWER.getType().equals(Integer.valueOf(record.getOpenType()))
						|| PrizeOpenTypeEnum.URL.getType().equals(Integer.valueOf(record.getOpenType()))) {
					if (StringUtil.isBlank(record.getSkipUrl())){
						return R.failed("请输入跳转链接");
					}

				}
			}
		}

		// 验证奖品配置参数
		if (CollectionUtils.isEmpty(record.getPrizeConfigList())) {
			return R.failed("请添加奖励配置信息");
		}
		if (PushPrizeTypeEnum.SINGLE.getType().equals(Integer.valueOf(record.getPushPrizeType()))) {
//			for (PrizeConfigReq prizeConfig : record.getPrizeConfigList()) {
//				// 如果是单个奖励,数据是完整的需要校验
//				// 如果是多个奖励，不需要校验，在创建奖励的时候已经校验了
//				// 验证奖品配置参数
//				R configParamResult = checkPrizeConfigParam(prizeConfig);
//				if (CommonConstants.FAIL.equals(configParamResult.getCode())) {
//					return configParamResult;
//				}
//			}
			if (record.getPrizeConfigList().size() > 1) {
				return R.failed("推送类型为[单个奖励]只能添加一个奖品配置信息");
			}
		}
		if (PushPrizeTypeEnum.MUTI.equals(Integer.valueOf(record.getPushPrizeType()))) {
			if (record.getPrizeConfigList().size() > 20) {
				return R.failed("推送类型为[组合奖励]最多添加20个奖品配置信息");
			}
		}
		String userGroupId = record.getUserGroupId();
		if (StringUtils.isNotBlank(userGroupId)){
			List<UserGroup> userGroupList = userGroupService.listByIds(Arrays.asList(userGroupId.split(",")));
			if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(userGroupList.stream().filter(v -> !v.getDimension().equals(record.getPushTarget())).collect(Collectors.toList()))){
				return R.failed("用户群组和推送目标不匹配");
			}
		}
		return R.ok();
	}

}
